package com.lagou.config;

import com.lagou.constants.StatementIdType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * mapper解析
 * @author sintang
 * @date 2020-09-02 23
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseConfig(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        // 获取到根 mapper
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        // 获取到所有select
        // 在这里添加insert
        // 在这里添加update
        // 在这里添加delete

        // 这里封装了一个枚举值，遍历枚举值，从而获取到select、insert、update、delete
        for (StatementIdType statementIdType : StatementIdType.values()) {
            List<Element> list = rootElement.selectNodes("//"+statementIdType.name());
            for (Element element : list) {
                parseElement(element,namespace,statementIdType);
            }
        }

    }

    /**
     * 提取公共方法解析element
     * @param element
     * @param statementIdType
     */
    private void parseElement(Element element, String namespace, StatementIdType statementIdType){
        String id = element.attributeValue("id");
        String paramterType = element.attributeValue("paramterType");
        String resultType = element.attributeValue("resultType");
        String sql = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setParamterType(paramterType);
        mappedStatement.setResultType(resultType);
        mappedStatement.setSql(sql);
        String key = namespace+"."+id;
        configuration.getMappedStatementMap().put(key,mappedStatement);
        configuration.getMappedStatementTypeMap().put(key,statementIdType);
    }

}
